package org.wallacefw.demo.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Order(1)
@Aspect
@Component
public class AspectjLog {

    private Logger logger = Logger.getLogger(AspectjLog.class);

    @Pointcut("execution(* org.wallacefw.demo.service.impl.*Service.*(..))")
    public void logAop(){}

    //z指定方法前拦截
    @Before("logAop() && args(..)")
    public void logBefore(JoinPoint joinPoint){
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        System.out.println("URL : " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD : " + request.getMethod());
        System.out.println("IP : " + request.getRemoteAddr());
        System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @After("logAop() && args(..)")
    public void logAfter(JoinPoint joinPoint){
        System.out.println("AspectjLog#After-------------------------");
    }

    @AfterReturning(returning = "ret", pointcut = "logAop()")
    public void doAfterReturning(Object ret){
        System.out.println("RESPONSE : " + ret.toString());
    }
}
